package com.gitee.wsl.jvm.reflect.autobox

import com.gitee.wsl.jvm.reflect.ReflectionUtils.cast

import java.math.BigDecimal

class IntegerTypeAutoboxer : TypeAutoboxer<Int> {
    override fun supports(type: Class<*>): Boolean {
        return Int::class.javaPrimitiveType == type || Int::class.java == type
    }

    override fun autobox(value: Any, type: Class<Int>): Int {
        if (value is Int) {
            return cast(value)
        } else if (value is BigDecimal) {
            return cast(value.toInt())
        } else if (value is String) {
            return cast(value.toInt())
        } else if (value is Long) {
            return cast(value.toInt())
        }
        throw UnsupportedOperationException(
            String.format(
                "Cannot autobox %s of type %s to %s",
                value,
                value.javaClass.name,
                Int::class.java.name
            )
        )
    }
}
